#!/usr/bin/env python3
#-*-coding:utf-8-*-
import os
import sys

#下载安装包及安装依赖
def Download():
    ECHO_STR1 = "安装依赖包 ..."
    print(ECHO_STR1)
    CMD1 = "yum -y install net-tools numactl pkgconfig perl perl-DBI perl-Compress-Raw-Bzip2 perl-Net-Daemon"
    os.system(CMD1)
    CMD2 = "yum -y install perl-Module-Pluggable perl-Pod-Escapes perl-Pod-Simple perl-libs perl-version"
    os.system(CMD2)
    CMD3 = "yum -y install perl-parent perl-Pod-Escapes perl-Pod-Simple perl-Time-HiRes perl-libs openssl-devel openssl"
    os.system(CMD3)
    CMD4 = "yum -y install libaio libaio-devel wget"
    os.system(CMD4)
    ECHO_STR2 = "安装依赖包完成 ！！！"
    print(ECHO_STR2)

    #ECHO_STR3 = "下载MySQL二进制安装包，版本：MySQL-5.7.28 ..."
    #print(ECHO_STR3)
    #CMD5 = "wget  https://cdn.mysql.com//Downloads/MySQL-5.7/mysql-5.7.28-linux-glibc2.12-x86_64.tar.gz"
    #res = os.system(CMD5)
    #if res != 0:
    #    ECHO_STR4 = "MySQL二进制包下载失败，请检查当前网络环境。"
    #    print(ECHO_STR4)
    #    sys.exit(1)

#安装及配置
def Install():
    ECHO_STR5 = "解压 ...."
    print(ECHO_STR5)
    CMD6 = "find . -name mysql*.tar.gz -exec tar -zxvf {} \;"
    res = os.system(CMD6)
    if res != 0:
        ECHO_STR6 = "MySQL二进制包解压失败，可能原因：包文件损坏，请删除文件重新执行此脚本。"
        print(ECHO_STR6)
        sys.exit(1)
    ECHO_STR7 = "解压成功 ！！！"
    print(ECHO_STR7)
    #移动到合适的位置：
    os.system("mv ./mysql*x86_64 /usr/local/mysql")

    # 创建MySQL用户，用户组，存放数据的文件，授权
    CMD7 = "groupadd mysql && useradd -r -g mysql -s /bin/false mysql"
    os.system(CMD7)

    #创建MySQL存放数据的文件夹，授权
    CMD8 = "mkdir -p /data/mysqldata/{data,logs} && chown mysql.mysql -R /data/mysqldata"
    os.system(CMD8)

    # 修改MySQL所有者权限
    CMD9 = "cd /usr/local/mysql && mkdir mysql-files && chmod 750 mysql-files && chown mysql.mysql -R /usr/local/mysql"
    os.system(CMD9)

    # 修改my.cnf文件
    random_number = os.popen("date +%N").read().strip("\n")
    f = open("/etc/my.cnf", mode="w")
    f.write("""[mysql]
# CLIENT #
port                           = 3306
socket                         = /data/mysqldata/mysql.sock

[mysqld]
# GENERAL #
user                           = mysql
default-storage-engine         = InnoDB
socket                         = /data/mysqldata/mysql.sock
pid-file                       = /data/mysqldata/mysql.pid
lower_case_table_names         = 1
sql_mode                       = 'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'

# MyISAM #
key-buffer-size                = 32M
myisam-recover-options         = FORCE,BACKUP

# SAFETY #
max-allowed-packet             = 16M
max-connect-errors             = 1000000

# DATA STORAGE #
datadir                        = /data/mysqldata/data/
basedir                        = /usr/local/mysql/
# BINARY LOGGING #
log-bin                        = /data/mysqldata/data/mysql-bin
expire-logs-days               = 14
sync-binlog                    = 1
server-id                      = {}

# CACHES AND LIMITS #
tmp-table-size                 = 32M
max-heap-table-size            = 32M
query-cache-type               = 0
query-cache-size               = 0
max-connections                = 500
thread-cache-size              = 50
open-files-limit               = 65535
table-definition-cache         = 4096
table-open-cache               = 4096

# INNODB #
innodb-flush-method            = O_DIRECT
innodb-log-files-in-group      = 2
innodb-log-file-size           = 128M
innodb-flush-log-at-trx-commit = 1
innodb-file-per-table          = 1
innodb-buffer-pool-size        = 2G

# LOGGING #
log-error                      = /data/mysqldata/logs/mysql-error.log
log-queries-not-using-indexes  = 1
slow-query-log                 = 1
slow-query-log-file            = /data/mysqldata/logs/mysql-slow.log""".format(random_number))
    f.close()
    # 初始化数据库
    CMD10 = "/usr/local/mysql/bin/mysqld --defaults-file=/etc/my.cnf --initialize --user=mysql"
    os.system(CMD10)
    # 输出信息
    CMD11 = "cat /data/mysqldata/logs/mysql-error.log |grep password"
    res = os.popen(CMD11).read().strip("\n").split(" ")
    print("*****************************************")
    print("*MySQL安装完成！                        *")
    print("*数据库账号/密码：root/" + res[-1] + "     *")
    print("*数据库安装位置：/usr/local/mysql       *")
    print("*数据文件位置：/data/mysqldata          *")
    print("*****************************************")

if __name__ == '__main__':
    Download()
    Install()


